package com._54programer.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class WebsocketServer {

    private int port;  //监听端口

    public WebsocketServer(int port) {
        this.port = port;
    }

    /**
     * 处理客户端请求
     */
    public void run() throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            //http编码和解码器
                            pipeline.addLast(new HttpServerCodec());

                            //以块的方式写, 添加ChunkedWritedHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());

                            //http数据在传输过程中是分段, 意思就是浏览器发送大量数据时,会发多次http请求, HttpObjectAggregator处理器可以将多个段聚合
                            pipeline.addLast(new HttpObjectAggregator(8192));

                            //将http协议升级为ws协议, 保持长连接
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

                            //IdleStateHandler, netty提供的处理空闲状态的处理器, 当IdleStateEvent被触发后, 就会传递给管道下一个handler去处理
                            //long readerIdleTime: 多长时间没读就会发送一个心跳检测包检测是否连接
                            //long writerIdleTime: 多长时间没写就会发送一个心跳检测包检测是否连接
                            //long allIdleTime: 多长时间没读写就会发送一个心跳检测包检测是否连接
                            pipeline.addLast(new IdleStateHandler(10, 20, 30, TimeUnit.SECONDS));

                            //添加一个队空闲检测进一步处理的Handler
                            pipeline.addLast(new IdleServerHandler());

                            //自定义处理器
                            pipeline.addLast(new WebSocketServerHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(10000).sync();
            //监听关闭
            channelFuture.channel().closeFuture().sync();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
